package com.example.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 手机验证码工具类
 */
@Component
public class MobileCaptchaUtil {
    @Autowired
    private RedisTemplate redisTemplate = RedisUtil.redis;
    @Value("${app.mobileCaptcha.prefix}")
    private String prefix; //验证码前缀
    @Value("${app.mobileCaptcha.expire}")
    private long expire; //验证码过期时间
    @Value("${app.mobileCaptcha.codeCount}")
    private int codeCount; //验证码数量

    public MobileCaptchaUtil() {
    }

    public MobileCaptchaUtil(RedisTemplate redisTemplate, String prefix, long expTime, int codeCount) {
        this.redisTemplate = redisTemplate;
        this.prefix = prefix;
        this.expire = expTime;
        this.codeCount = codeCount;
    }

    /**
     * 获取图片验证码
     * @param mobile
     */
    public void getCaptcha(String mobile){
        // 这里不做格式校验,获得生成的验证码字符
        String code = RandomUtil.randomEleSet(CollUtil.newArrayList(1,2,3,4,5,6,7,8,9,0), this.codeCount).stream()
                .map(Object::toString)
                .collect(Collectors.joining());
        // 存储到redis
        redisTemplate.opsForValue().set(this.prefix+mobile,code,this.expire, TimeUnit.SECONDS);
    }

    /**
     * 验证验证码是否输入正确
     * @param mobile
     * @param code
     * @return
     */
    public boolean checkCaptcha(String mobile,String code){
        boolean isExpire = new RedisUtil().isExpire(this.prefix+mobile);
        if(isExpire){
            return false;
        }
        String redisCode = String.valueOf(this.redisTemplate.opsForValue().get(this.prefix+mobile));
        if (code.equals(redisCode)){
            //删除验证成功后的codeSign
            this.redisTemplate.delete(this.prefix+mobile);
            return true;
        }else{
            return false;
        }
    }
}
